package com.itfitness.mchart.activity;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.hyphenate.chat.EMClient;
import com.hyphenate.easeui.domain.EaseUser;
import com.itfitness.mchart.R;
import com.itfitness.mchart.utils.ListUtil;
import com.itfitness.mchart.utils.MTextUtil;

import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

/**
 * @ProjectName: MChart
 * @Package: com.itfitness.mchart.activity
 * @ClassName: AddFriendActivity
 * @Description: java类作用描述 ：
 * @Author: 作者名：lml
 * @CreateDate: 2019/4/24 17:05
 * @UpdateUser: 更新者：
 * @UpdateDate: 2019/4/24 17:05
 * @UpdateRemark: 更新说明：
 * @Version: 1.0
 */

public class AddFriendActivity extends BaseActivity {
    @BindView(R.id.activity_addfriend_et_usernam)
    EditText activityAddfriendEtUsernam;
    @BindView(R.id.activity_addfriend_tv_usernam)
    TextView activityAddfriendTvUsernam;
    @BindView(R.id.activity_addfriend_bt_add)
    Button activityAddfriendBtAdd;
    @BindView(R.id.activity_addfriend_layout_searchfriend)
    LinearLayout activityAddfriendLayoutSearchfriend;

    @Override
    protected int LayoutRes() {
        return R.layout.activity_addfriend;
    }

    @Override
    protected boolean isHaveTitle() {
        return true;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ButterKnife.bind(this);
        initDatas();
    }

    private void initDatas() {
        setTitle("添加好友", R.color.colorTitleText);
        setRightTitle("查找", R.color.colorTitleText, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                searchFriend();
            }
        });
    }

    /**
     * 查找好友
     */
    private void searchFriend() {
        String username = MTextUtil.getText(activityAddfriendEtUsernam);
        if (TextUtils.isEmpty(username)) {
            ToastUtils.showShort("请输入要查找的用户名");
        } else {
            activityAddfriendTvUsernam.setText(username);
            activityAddfriendLayoutSearchfriend.setVisibility(View.VISIBLE);
        }
    }

    @OnClick(R.id.activity_addfriend_bt_add)
    public void onViewClicked() {
        checkIsFriend();
    }

    /**
     * 判断是否已经是好友
     */
    private void checkIsFriend() {
        Observable.create(new ObservableOnSubscribe<List<String>>() {
            @Override
            public void subscribe(ObservableEmitter<List<String>> emitter) throws Exception {
                List<String> allContactsFromServer = EMClient.getInstance().contactManager().getAllContactsFromServer();
                emitter.onNext(allContactsFromServer);
            }
        }).subscribeOn(Schedulers.newThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<List<String>>() {
                    @Override
                    public void accept(List<String> allContactsFromServer) throws Exception {
                        if (allContactsFromServer != null && allContactsFromServer.size()>0) {
                            for(String username:allContactsFromServer){
                                if(username.trim().equals(MTextUtil.getText(activityAddfriendEtUsernam))){
                                    ToastUtils.showShort("你们已经是好友了");
                                    return;
                                }
                            }
                            addFriend();
                        }else {
                            addFriend();
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        LogUtils.eTag("获取联系人", throwable.getMessage());
                        ToastUtils.showShort("查找好友失败，请重试");
                    }
                });
    }

    /**
     * 执行添加好友逻辑
     */
    private void addFriend() {
        Observable.create(new ObservableOnSubscribe<Integer>() {
            @Override
            public void subscribe(ObservableEmitter<Integer> emitter) throws Exception {
                //参数为要添加的好友的username和添加理由
                LogUtils.eTag("添加好友",MTextUtil.getText(activityAddfriendTvUsernam));
                EMClient.getInstance().contactManager().addContact(MTextUtil.getText(activityAddfriendTvUsernam), "添加好友");

                emitter.onNext(1);
            }
        }).subscribeOn(Schedulers.newThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Integer>() {
                    @Override
                    public void accept(Integer integer) throws Exception {
                        if (integer == 1) {
                            ToastUtils.showShort("发送添加好友邀请成功");
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        LogUtils.eTag("添加好友", throwable.getMessage());
                        ToastUtils.showShort("发送添加好友邀请失败，请重试");
                    }
                });
    }
}
